<template>
  <div class="temp-page">
    <div id="container" :key="state.changeInitKey"></div>
  </div>
</template>

<script setup name="caseGraphDialog">
//import { queryTreeExpand } from '@/api/smartScreen/index';
import G6 from '@antv/g6';
import * as _ from 'lodash'
import { data as treeDataJson } from './treeData'
const emit = defineEmits([''])
const props = defineProps({
  //是否显示根节点查询父级
  isQueryParent: {
    type: Boolean,
    default: true
  },
  treeData: {
    type: Object,
    default: () => {
      return {
        key: "A",
        name: "测试休息休息下下小行星测试休息休息下下小行星行星测试休息休息下下小行星"
      }
    }
  }
})
const state = reactive({
  id: '',
  isLoading: true,
  mappingData: { edges: [] },
  errinfo: '',
  rootData: {},
  changeInitKey: 0,
  typeArray: [],
  listDate: {},
});
let data = {
  id: 'A',
  name: props.treeData.name,
  label: '',
  isRoot: props.isQueryParent,
  children: [
    { id: 'A1', key: props.treeData.key, type: "", labelType: "xxx1", name: "x", label: "企业主要人员", children: [{ id: 'A5', key: "A5", type: "", labelType: "xxx1", name: "企业主要人员x", label: "企业主要人员X" }] },
    { id: 'A2', key: props.treeData.key, type: "", labelType: "xxx2", name: "x", label: "企业分支机构" },
    { id: 'A3', key: props.treeData.key, type: "", labelType: "xxx3", name: "x", label: "被投资关系" },
    { id: 'A4', key: props.treeData.key, type: "", labelType: "xxx4", name: "x", label: "投资关系" },
  ],
};
function query(val, nodeId, isParent = false) {
  const childData = []
  if (nodeId === 'Classification') {
    treeDataJson.children[0].children.forEach(item => {
      childData.push({
        id: item.id,
        key: item.id,
        name: item.name,
        faren: item.faren,
        isParent: isParent,
        lineType: item.lineType,
        level: item.level,
      })
    })
  } else if (nodeId === 'Consensus') {
    treeDataJson.children[1].children.forEach(item => {
      childData.push({
        id: item.id,
        key: item.id,
        name: item.name,
        faren: item.faren,
        isParent: isParent,
        lineType: item.lineType,
        level: item.level,
      })
    })
  } else if (nodeId === 'Regression') {
    treeDataJson.children[2].children.forEach(item => {
      childData.push({
        id: item.id,
        key: item.id,
        name: item.name,
        faren: item.faren,
        isParent: isParent,
        lineType: item.lineType,
        level: item.level,
      })
    })
  } else {
    treeDataJson.children.forEach(item => {
      childData.push({
        id: item.id,
        key: item.id,
        name: item.name,
        faren: item.faren,
        isParent: isParent,
        lineType: item.lineType,
        level: item.level,
      })
    })
  }

  const parentData = graph.findDataById(nodeId);
  if (!parentData.children) {
    parentData.children = [];
  }
  parentData.children = childData;
  graph.changeData();
  return
  queryTreeExpand({
    direction: "",
    id: val.key,
    label: "",
    relation: val.label,
    limit: 10,
    direction: isParent ? '反向' : '正向'
  }).then(res => {
    const childData = []
    res.forEach(item => {
      if (item.type == '企业人员') {
        childData.push({
          id: item.id,
          key: item.id,
          name: item.name,
          zw: item.zw,
        })
      } else {
        childData.push({
          id: item.id,
          key: item.id,
          name: item.name,
          faren: item.faren,
          isParent: isParent,
        })
      }
    })
    const parentData = graph.findDataById(nodeId);
    if (!parentData.children) {
      parentData.children = [];
    }
    parentData.children = childData;
    graph.changeData();
  })
}
let graph = {}
function initCharts(val, type = 1) {//type===1时为企业图谱
  G6.registerNode('root', {
    draw: (cfg, group) => {
      const size = [120, 60];
      const keyShape = group.addShape('rect', {
        attrs: {
          width: size[0],
          height: size[1],
          x: -size[0] / 2,
          y: -size[1] / 2,
          fill: 'rgb(218, 71, 81)',
          radius: 1
        },
        draggable: true,
        name: 'root-keyshape'
      });
      group.addShape('text', {
        attrs: {
          text: `${cfg.label}`,
          fill: 'rgba(255, 255, 255, 0.85)',
          fontSize: 10,
          //x: -36,
          y: -10,
          textAlign: 'center'
        },
        draggable: true,
        name: 'label-shape'
      });
      group.addShape('image', {
        attrs: {
          x: -70,
          y: -10,
          width: 20,
          height: 20,
          img: 'https://gw.alipayobjects.com/zos/basement_prod/012bcf4f-423b-4922-8c24-32a89f8c41ce.svg',
        },
        name: 'image-shape',
      });
      return keyShape;
    }
  });

  // level1 node
  G6.registerNode('level1node', {
    draw: (cfg, group) => {
      let color = 'rgb(254,147,170)'
      if (cfg.lineType == 'type2') {
        color = 'rgb(0,147,253)'
      } else if (cfg.lineType == 'type1') {
        color = 'rgb(255,154,35)'
      }
      const size = [120, 60];
      const keyShape = group.addShape('rect', {
        attrs: {
          width: size[0],
          height: size[1],
          x: -size[0] / 2,
          y: -size[1] / 2,
          fill: color,
          radius: 1
        },
        draggable: true,
        name: 'level1node-keyshape'
      });
      group.addShape('text', {
        attrs: {
          text: `${cfg.label}`,
          fill: '#fff',
          fontSize: 12,
          x: 0,
          y: -6,
          textAlign: 'center'
        },
        draggable: true,
        name: 'label-shape'
      });
      group.addShape('image', {
        attrs: {
          x: -70,
          y: -10,
          width: 20,
          height: 20,
          img: cfg.img,
        },
        name: 'image-shape',
      });
      return keyShape;
    },
    update: undefined,
  }, 'rect')

  // other node
  G6.registerNode('othernode', {
    draw: (cfg, group) => {
      let color = 'rgb(128,177,254)'
      if (cfg.lineType == 'type2') {
        color = 'rgb(0,147,253)'
      } else if (cfg.lineType == 'type1') {
        color = 'rgb(255,154,35)'
      } else if (cfg.lineType == 'type3') {
        color = 'rgb(254,144,196)'
      }
      const size = [100, 30];
      const keyShape = group.addShape('rect', {
        attrs: {
          x: -5,
          y: -5,
          width: 30, //200,
          height: 30, // 60
          //stroke: color,
          radius: 15,
          fill: color,
          color: "#fff"
        },
        name: 'main-box',
        draggable: true,
      });
      group.addShape('image', {
        attrs: {
          //x: -w + 5,
          //y: -h + 5,
          width: 20,
          height: 20,
          img: cfg.img,
        },
        name: 'image-shape',
      });
      group.addShape('text', {
        attrs: {
          text: `${cfg.label}`,
          fill: '#333',
          fontSize: 6,
          x: 0,
          y: 36,
          textAlign: 'center'
        },
        draggable: true,
        name: 'label-shape'
      });
      return keyShape;
    },
    update: undefined
  }, 'rect')
  const toolbar = new G6.ToolBar({
    position: { x: 10, y: 10 },
  });
  let data = treeDataJson
  if (type != 1) {
    data = {
      id: val.key,
      isRoot: props.isQueryParent,
      name: val.name,
      label: '',
      lineType: "root",
      key: val.key,
      level: 0,
      collapsed: true,
    };
  }
  const container = document.getElementById('container');
  const width = container.scrollWidth;
  const height = container.scrollHeight || 500;
  graph = new G6.TreeGraph({
    container: 'container',
    width,
    height,
    plugins: [toolbar],
    linkCenter: true,
    fitViewPadding: [300, 300, 300, 300],
    modes: {
      default: [
        // {
        //   type: 'collapse-expand',
        //   onChange: function onChange(item, collapsed) {
        //     const data = item.get('model');
        //     data.collapsed = collapsed;
        //     return true;
        //   },
        // },
        'drag-canvas',
        'zoom-canvas',
      ],
    },
    defaultEdge: {
      type: 'extra-shape-edge',
      style: {
        endArrow: {
          path: G6.Arrow.triangle(10, 12, 25),
          d: 25,
          fill: '#fff',
          //stroke: '#0f0',
        },
      },
      labelCfg: {
        autoRotate: true,
        style: {
          fill: '#bbbbbd',
          stroke: 'white',
          lineWidth: 14,
        }
      },
    },
    defaultNode: {
      size: 26,
    },
    layout: {
      type: 'dendrogram',
      direction: 'LR',
      nodeSep: 20,
      rankSep: 200,
      radial: true,
    },
  });
  // G6.Util.traverseTree(data, subtree => {
  //   if (subtree.level === undefined) subtree.level = 0;
  //   subtree.children?.forEach(child => child.level = subtree.level + 1);
  //   switch (subtree.level) {
  //     case 0:
  //       subtree.type = 'root';
  //       break;
  //     case 1:
  //       subtree.type = 'level1node';
  //       break;
  //     default:
  //       subtree.type = 'othernode';
  //   }
  // });
  graph.node(function (node) {
    let type = 'root'
    switch (node.level) {
      case 0:
        type = 'root';
        break;
      case 1:
        type = 'level1node';
        break;
      default:
        type = 'othernode';
    }
    return {
      type,
      label: node.id,
    };
  });
  graph.edge(function (val) {
    return setEdgeColor(val.source, val.target)
  });
  graph.data(data);
  graph.render();
  graph.fitView();
  graph.on('node:click', function (evt) {
    const item = evt.item;
    const nodeId = item.get('id');
    const model = item.getModel();
    const children = model.children;
    if (evt.target.get('name') === 'collapse-icon') {
      //处理加减号节点点击事件
      let childList = evt.item.getModel().children ? evt.item.getModel().children : []
      let isParent = true
      childList.filter(item => {
        if (item.nodeType == "parent") {
          isParent = false
        }
      })
      if (isParent) {
        query(model, nodeId, true)
      }
      evt.item.getModel().collapsed = !evt.item.getModel().collapsed;
      graph.setItemState(evt.item, 'collapsed', evt.item.getModel().collapsed);
      graph.layout();
    } else {
      if (!children || children.length === 0) {
        query(model, nodeId)
      } else {
        evt.item.getModel().collapsed = !evt.item.getModel().collapsed;
        graph.layout();
      }
    }
  });
  if (typeof window !== 'undefined')
    window.onresize = () => {
      if (!graph || graph.get('destroyed')) return;
      if (!container || !container.scrollWidth || !container.scrollHeight) return;
      graph.changeSize(container.scrollWidth, container.scrollHeight);
    };

}
const colorArr = [
  {
    type: "root",
    color: 'rgb(255,154,35)',
  },
  {
    type: "type1",
    color: 'rgb(254,147,170)',
  },
  {
    type: "type2",
    color: 'rgb(0,147,253)',
  },
  {
    type: "type3",
    color: 'rgb(254,144,196)',
  },
]
function setEdgeColor(source, target) {
  //设置线相关属性
  let color = "#c1c3c5"
  let label = 'xx'
  data.children.forEach((item, index) => {
    if (item.id == source) {
      label = item.labelType
      color = colorArr[index].color
    }
  })
  if (source == 'Consensus') {
    color = colorArr[2].color
  } else if (source == 'Regression') {
    color = colorArr[3].color
  } else if (source == 'Classification') {
    color = colorArr[0].color
  }
  if (target == 'Consensus') {
    color = colorArr[2].color
  } else if (target == 'Regression') {
    color = colorArr[3].color
  } else if (target == 'Classification') {
    color = colorArr[0].color
  }
  return {
    //type: 'cubic-horizontal',
    color,
    label,
    labelCfg: {
      autoRotate: true,
      style: {
        fill: color,
        stroke: 'white',
        lineWidth: 14,
      }
    },
  };
}
defineExpose({})

onMounted(() => {
  // root node
  initCharts({ name: "根节点" }, 2)
});
</script>

<style lang="scss" scoped>
.temp-page {
  position: relative;
  width: 100%;
  height: 100%;

  #container {
    width: 100%;
    height: 100%;
  }
}

.inner-dialog {
  position: absolute;
  top: 50px;
  right: 50px;
  width: 300px;
  height: 550px;
  padding: 10px;
  background-color: #fbfcfc;
  border-radius: 10px;
  box-shadow: 0px 2px 4px rgba(10, 10, 20, 0.5);

  .inner-dialog-title {
    height: 30px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
  }

  .info-list {
    margin-bottom: 10px;

    .info-list-title {
      color: #000;
    }
  }
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>
